<template>
  <div class="geographical-query-container">
    <div class="map-container" ref="mapContainer">
    </div>

    <!-- Control Panel -->
    <div class="control-panel" id="tools-container">
      <h3 class="panel-title">地理范围查询</h3>
      <p class="panel-description">绘制多边形区域查询设施</p>

      <el-button
        type="primary"
        @click="startDrawArea"
        :disabled="isDrawingArea"
        class="draw-button"
        style="margin-bottom: 10px"
      >
        <el-icon><Aim /></el-icon> 绘制查询区域
      </el-button>

      <el-button
        type="warning"
        @click="cancelDrawArea"
        class="draw-button"
      >
        <el-icon><Close /></el-icon> 清除绘制范围
      </el-button>
    </div>

    <!-- Feature Attributes Dialog -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" :modal="false">
      <el-form label-width="120px" class="attribute-form">
        <template v-for="(value, key) in attributes" :key="key">
          <!-- 图片字段 -->
          <el-form-item v-if="key === 'FacilityImage' || key === 'RoadImage'" :label="getLabel(key)">
            <el-image
              v-if="value"
              :src="value"
              fit="cover"
              class="attribute-image"
              :preview-src-list="[value]"
            />
            <div v-else class="no-image">暂无图片</div>
          </el-form-item>
          <!-- 介绍字段 -->
          <el-form-item v-else-if="key === 'FacilityIntroduction'" :label="getLabel(key)">
            <div class="introduction-text">{{ value || '无介绍' }}</div>
          </el-form-item>
          <!-- OtherJson 详细信息字段 -->
          <el-form-item v-else-if="key === 'OtherJson'" :label="getLabel(key)">
            <div class="introduction-text">{{ formatOtherJson(value) }}</div>
          </el-form-item>
          <!-- 状态字段 -->
          <el-form-item
            v-else-if="key === 'Status' && attributes.facilitytype"
            :label="getStatusLabel(attributes.facilitytype, key as string)"
          >
            {{ value || '无数据' }}
          </el-form-item>
          <!-- 其他普通字段 -->
          <el-form-item
            v-else-if="typeof value !== 'object' && key !== 'objectid' && key !== 'FacilityImage' && key !== 'RoadImage' && key !== 'FacilityIntroduction' && key !== 'Status' && key !== 'OtherJson'"
            :label="getLabel(key as string)"
          >
            {{ value || '无数据' }}
          </el-form-item>
        </template>
      </el-form>
    </el-dialog>

    <!-- Multiple Features Selection Dialog -->
    <el-dialog v-model="selectDialogVisible" title="请选择要素" width="500px" :modal="false">
      <template #header>
        <div class="dialog-header">
          <span>请选择要素</span>
        </div>
      </template>
      <div class="feature-selector">
        <el-table :data="selectedFeatures" style="width: 100%" class="feature-table">
          <el-table-column prop="attributes.facilityname || attributes.RoadName" label="名称">
            <template #default="{ row }">
              {{ row.attributes.facilityname || row.attributes.RoadName || '未命名要素' }}
            </template>
          </el-table-column>
          <el-table-column prop="layer.id" label="要素类型">
            <template #default="{ row }">
              {{ getLayerType(row.layer.id) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="{ $index }">
              <el-button type="primary" size="small" @click="handleSelect($index)" class="select-btn">
                选择
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- Area Results Panel -->
    <el-card
      v-if="showAreaResults"
      class="area-results-panel"
      :body-style="{ padding: '10px' }"
    >
      <template #header>
        <div class="results-header">
          <span>范围内的设施</span>
          <div>
            <el-button
              type="primary"
              size="small"
              @click="showSelectedAreaResults"
              :disabled="selectedAreaFeatures.length === 0"
            >
              查看选中
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="closeAreaResults"
              class="close-button"
            >
              <el-icon><Close /></el-icon>
            </el-button>
          </div>
        </div>
      </template>

      <el-scrollbar height="300px">
        <el-checkbox-group v-model="selectedAreaFeatures">
          <div v-for="(feature, index) in areaFeatures" :key="index" class="result-item">
            <el-checkbox :label="index">
              {{ feature.attributes.facilityname || '未命名设施' }}
            </el-checkbox>
          </div>
        </el-checkbox-group>
      </el-scrollbar>
    </el-card>

    <!-- Drawing Area Panel -->
    <el-card
      v-if="isDrawingArea"
      class="drawing-panel"
      :body-style="{ padding: '10px', height: '10px' }"
    >
      <template #header>
        <div class="results-header">
          <span>绘制范围</span>
          <el-button type="danger" size="small" @click="cancelDrawArea" class="close-button">
            取消
          </el-button>
        </div>
      </template>
      <div class="drawing-instructions">
        <p>请在地图上点击绘制多边形区域</p>
        <p>双击完成绘制</p>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Aim, Close } from '@element-plus/icons-vue'
import Graphic from '@arcgis/core/Graphic'
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import Query from '@arcgis/core/rest/support/Query.js'
import Handles from '@arcgis/core/core/Handles.js'
import SketchViewModel from '@arcgis/core/widgets/Sketch/SketchViewModel'
import Polygon from '@arcgis/core/geometry/Polygon.js'
import SimpleLineSymbol from '@arcgis/core/symbols/SimpleLineSymbol'
import PictureMarkerSymbol from '@arcgis/core/symbols/PictureMarkerSymbol'
import GraphicsLayer from '@arcgis/core/layers/GraphicsLayer'
import gaodeLayer from '@/utils/GaoDeBaseLayer'
import {
  facilityPointSymbol,
  scenicPointSymbol,
  viewScenicSpotSymbol,
  serviceSymbol,
  monitorSymbol,
  trafficSymbol,
  greenSymbol
} from '@/utils/facilityIcons'

const mapContainer = ref<HTMLDivElement>()

// 使用统一的设施图标符号（已从 facilityIcons.ts 导入）

// Create road symbol
const roadSymbol = new SimpleLineSymbol({
  color: [0, 122, 194, 0.8],
  width: 4,
  style: 'solid',
  cap: 'round',
  join: 'round',
})

// Create facility layer
const facilityLayer = new FeatureLayer({
  url: 'https://services.arcgis.com/cxicHGWOCJwYXasp/arcgis/rest/services/Facility/FeatureServer/0',
  outFields: ['*'],
  renderer: {
    type: 'unique-value',
    field: 'facilitytype',
    defaultSymbol: facilityPointSymbol,
    uniqueValueInfos: [
      {
        value: '驿站',
        symbol: scenicPointSymbol,
      },
      {
        value: '景点',
        symbol: viewScenicSpotSymbol,
      },
      {
        value: '餐饮',
        symbol: facilityPointSymbol,
      },
    ],
  } as never,
})

// Create road layer
const roadLayer = new FeatureLayer({
  url: 'https://www.geosceneonline.cn/server/rest/services/Hosted/S103/FeatureServer/0',
  outFields: ['*'],
  renderer: {
    type: 'simple',
    symbol: roadSymbol,
  } as never,
})

// Create sketch layer for drawing
const sketchLayer = new GraphicsLayer({
  title: '绘图图层',
})

// Create map
const map = new Map({
  basemap: {
    baseLayers: [gaodeLayer],
  },
})

// Add layers to map
map.add(facilityLayer)
map.add(roadLayer)
map.add(sketchLayer)

// Create map view
const view = new MapView({
  map: map,
  center: [117.14435714426122, 36.29746937366678],
  zoom: 10,
})

// State variables
const dialogVisible = ref(false)
const attributes = ref<{ [key: string]: any }>({})
const dialogTitle = ref('要素属性')
const selectDialogVisible = ref(false)
const selectedFeatures = ref<any[]>([])
const selectedFeatureIndex = ref(0)
const highlightHandle: Handles = new Handles() // 高亮显示句柄
let selectFeatureLayer: FeatureLayer | null = null
let selectGraphic: Graphic | null = null
let allSelectGraphics: Graphic[] = []

// Area query related state
const isDrawingArea = ref(false)
let sketchViewModel: SketchViewModel | null = null
let areaFeatures: Graphic[] | null = null
const showAreaResults = ref(false)
const selectedAreaFeatures = ref<number[]>([])

// Initialize sketch view model
function initSketchViewModel() {
  if (!sketchViewModel) {
    sketchViewModel = new SketchViewModel({
      view: view,
      layer: sketchLayer,
      polygonSymbol: {
        type: 'simple-fill',
        color: [51, 51, 204, 0.2],
        style: 'solid',
        outline: {
          color: [51, 51, 204, 1],
          width: 2,
        },
      },
    })

    // Drawing complete event
    sketchViewModel.on('create', async (event) => {
      if (event.state === 'complete') {
        const geometry = event.graphic.geometry as Polygon
        await queryFeaturesInArea(geometry)
        isDrawingArea.value = false
      }
    })
  }
}

// Start drawing area
function startDrawArea() {
  if (!sketchViewModel) {
    initSketchViewModel()
  }

  // 重置状态和清除之前的结果
  showAreaResults.value = false
  selectedAreaFeatures.value = []
  areaFeatures = null

  // 清除之前的绘制
  sketchLayer.removeAll()
  view.graphics.removeAll() // 清除视图上的所有图形，包括高亮显示
  highlightHandle.removeAll() // 清除所有高亮句柄

  isDrawingArea.value = true
  sketchViewModel?.create('polygon')
  ElMessage.info('请在地图上绘制一个区域')
}

// Cancel drawing area
function cancelDrawArea() {
  // 取消当前绘图操作
  if (sketchViewModel) {
    sketchViewModel.cancel()
  }

  // 重置状态
  isDrawingArea.value = false
  showAreaResults.value = false
  selectedAreaFeatures.value = []
  areaFeatures = null

  // 清除图层上的所有图形
  sketchLayer.removeAll()

  // 确保图层可见性正确
  sketchLayer.visible = true

  console.log('已清除所有绘制的范围')
  ElMessage.success('已清除所有绘制的范围')
}

// Query features in area
async function queryFeaturesInArea(geometry: __esri.Polygon) {
  try {
    // Create spatial query
    const query = new Query({
      geometry: geometry,
      spatialRelationship: 'intersects',
      outFields: ['*'],
      returnGeometry: true,
    })

    // Query facility layer
    const result = await facilityLayer.queryFeatures(query)
    areaFeatures = result.features

    if (areaFeatures.length === 0) {
      ElMessage.info('所选区域内没有设施')
    } else {
      showAreaResults.value = true
      selectedAreaFeatures.value = [] // Clear selected items
      ElMessage.success(`在所选区域内找到 ${areaFeatures.length} 个设施`)
    }
  } catch (error) {
    console.error('区域查询失败:', error)
    ElMessage.error('区域查询失败')
  }
}

// Close area results panel
function closeAreaResults() {
  showAreaResults.value = false

  // 清除绘制的图形，但保留查询结果
  // 这样用户可以再次打开结果面板查看
  sketchLayer.removeAll()

  ElMessage.info('已关闭结果面板，可以开始新的查询')
}

// Show selected area results
function showSelectedAreaResults() {
  if (selectedAreaFeatures.value.length === 0) {
    ElMessage.warning('请至少选择一个设施')
    return
  }

  // Get selected graphics
  const selectedGraphics = selectedAreaFeatures.value.map((index) => areaFeatures![index])

  // If only one result, show attributes directly
  if (selectedGraphics.length === 1) {
    selectFeatureLayer = facilityLayer
    selectGraphic = selectedGraphics[0]
    showAttributes(selectedGraphics[0])
  } else {
    // Multiple results show selection dialog
    selectedFeatures.value = selectedGraphics.map((g) => ({
      attributes: structuredClone(g.attributes),
      geometry: structuredClone(g.geometry),
      layer: { id: facilityLayer.id },
    }))
    allSelectGraphics = selectedGraphics
    selectedFeatureIndex.value = 0
    selectDialogVisible.value = true
  }

  // Close area results panel
  showAreaResults.value = false
}

// Get layer type based on layer ID
function getLayerType(id: string) {
  if (id === facilityLayer.id) {
    return '设施'
  } else if (id === roadLayer.id) {
    return '道路'
  }
  return '未知类型'
}

// Handle feature selection
function handleSelect(index: number) {
  selectedFeatureIndex.value = index
  confirmSelection()
}

// Confirm feature selection
function confirmSelection() {
  selectFeatureLayer = facilityLayer
  selectGraphic = allSelectGraphics[selectedFeatureIndex.value]
  showAttributes(selectedFeatures.value[selectedFeatureIndex.value] as __esri.Graphic)
  selectDialogVisible.value = false
}

// Initialize map view in onMounted
onMounted(() => {
  // Initialize map view container
  view.container = mapContainer.value as HTMLDivElement
  view.ui.add('tools-container', 'top-right')
})

// Show feature attributes
function showAttributes(feature: __esri.Graphic) {
  // Clear previous highlight
  highlightHandle.removeAll()

  // Highlight selected feature
  if (selectFeatureLayer && selectGraphic) {
    // Create a highlight graphic
    const highlightSymbol = selectFeatureLayer.id === facilityLayer.id
      ? {
          type: 'simple-marker',
          style: 'circle',
          color: [255, 255, 0, 0.8],
          size: '16px',
          outline: {
            color: [255, 255, 0, 0.8],
            width: 3
          }
        }
      : {
          type: 'simple-line',
          color: [255, 255, 0, 0.8],
          width: 6
        };

    const highlightGraphic = new Graphic({
      geometry: selectGraphic.geometry,
      symbol: highlightSymbol as any
    });

    // Add highlight graphic to view
    view.graphics.add(highlightGraphic);

    // Store the highlight handle for later removal
    highlightHandle.add({
      remove: () => {
        view.graphics.remove(highlightGraphic);
      }
    });
  }

  // Set dialog title based on feature type
  if (feature.layer?.id === facilityLayer.id) {
    dialogTitle.value = `设施: ${feature.attributes.facilityname || '未命名设施'}`
  } else if (feature.layer?.id === roadLayer.id) {
    dialogTitle.value = `道路: ${feature.attributes.RoadName || '未命名道路'}`
  } else {
    dialogTitle.value = '要素属性'
  }

  // Set attributes and show dialog
  attributes.value = feature.attributes
  dialogVisible.value = true

  // Zoom to the feature
  view.goTo({
    target: feature.geometry,
    zoom: 15
  });
}

// Get label for attribute field
function getLabel(key: string) {
  const labelMap: { [key: string]: string } = {
    facilityname: '设施名称',
    facilitytype: '设施类型',
    FacilityIntroduction: '设施介绍',
    FacilityImage: '设施图片',
    Status: '状态信息',
    OtherJson: '详细信息',
    RoadName: '道路名称',
    RoadType: '道路类型',
    RoadLength: '道路长度',
    RoadImage: '道路图片',
    OwnerRoad: '所属道路',
    objectid: '对象ID',
  }
  return labelMap[key] || key
}

// 格式化 OtherJson 字段显示
function formatOtherJson(value: string) {
  if (!value) return '暂无详细信息'
  try {
    const data = JSON.parse(value)
    let formatted = ''
    for (const [key, val] of Object.entries(data)) {
      if (val !== null && val !== undefined && val !== '') {
        formatted += `${key}: ${val}\n`
      }
    }
    return formatted || '暂无详细信息'
  } catch {
    return value
  }
}

// 根据设施类型获取状态标签
function getStatusLabel(facilitytype: string, key: string) {
  if (key !== 'Status') return getLabel(key)

  switch (facilitytype) {
    case '驿站':
      return '设备状态'
    case '景点':
      return '开放状态'
    case '餐饮':
      return '营业状态'
    default:
      return '状态信息'
  }
}
</script>

<style scoped>
.geographical-query-container {
  height: 100%;
  width: 100%;
  position: relative;
}

.map-container {
  height: 100%;
  width: 100%;
  position: relative;
}

/* Control panel styles */
.control-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 1000;
  background: rgba(24, 44, 78, 0.85);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.15);
  transition: all 0.3s ease;
  color: #fff;
  width: 280px;
}

.panel-title {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 18px;
  color: #fff;
}

.panel-description {
  margin-bottom: 15px;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

.draw-button {
  width: 100%;
}

/* Dialog styles */
:deep(.el-dialog) {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  box-shadow: 0 15px 40px rgba(0, 0, 0, 0.3);
  border: none;
  overflow: hidden;
  backdrop-filter: blur(10px);
}

:deep(.el-dialog__header) {
  background: linear-gradient(135deg, #1976D2, #42A5F5);
  color: white;
  padding: 15px;
  border-bottom: none;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
  font-weight: 600;
  color: white;
}

.attribute-form {
  padding: 10px;
}

.attribute-image {
  width: 100%;
  max-height: 200px;
  border-radius: 8px;
  cursor: pointer;
}

.no-image {
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  color: #909399;
  border-radius: 8px;
}

.introduction-text {
  max-height: 150px;
  overflow-y: auto;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 8px;
  color: #333;
  line-height: 1.5;
}

.feature-selector {
  max-height: 300px;
  overflow-y: auto;
}

.feature-table {
  border-radius: 8px;
  overflow: hidden;
}

.select-btn {
  padding: 4px 12px;
}

/* Panel styles */
.area-results-panel {
  position: fixed;
  left: 20px;
  top: 20px;
  width: 320px;
  z-index: 1500;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  border: none;
  overflow: hidden;
  backdrop-filter: blur(10px);
}

.drawing-panel {
  position: fixed;
  left: 50%;
  top: 20px;
  transform: translateX(-50%);
  width: 320px;
  height: 150px;
  z-index: 1600;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  border: none;
  overflow: hidden;
  backdrop-filter: blur(10px);
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
  font-weight: 600;
  color: white;
}

:deep(.el-card__header) {
  background: linear-gradient(135deg, #1976D2, #42A5F5);
  color: white;
  padding: 12px 15px;
  border-bottom: none;
}

.close-button {
  padding: 5px 12px;
  background: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;
  transition: all 0.3s ease;
}

.result-item {
  padding: 8px;
  border-bottom: 1px solid #ebeef5;
}

.result-item:last-child {
  border-bottom: none;
}

.drawing-instructions {
  text-align: center;
  color: #333;
  font-size: 14px;
  line-height: 1.5;
}
.el-button + .el-button{
  margin-left: 0;
}
</style>
